/*
* Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
*/
package com.hyyt.shopjsp.redis.service.impl;


import com.hyyt.shopjsp.basic.pojo.BasicKeyBook;
import com.hyyt.shopjsp.basic.pojo.BasicSystemConfig;
import com.hyyt.shopjsp.basic.service.IBasicKeyBookService;
import com.hyyt.shopjsp.basic.service.IBasicSystemConfigService;
import com.hyyt.shopjsp.basic.vo.BasicStatusRelateVo;
import com.hyyt.shopjsp.home.pojo.ShopHomeKeyBook;
import com.hyyt.shopjsp.home.service.IShopHomeKeyBookService;
import com.hyyt.shopjsp.phone.pojo.PhoneHomeKeyBook;
import com.hyyt.shopjsp.phone.service.IPhoneHomeKeyBookService;
import com.hyyt.shopjsp.product.vo.AllProductTypeVo;
import com.hyyt.shopjsp.product.pojo.ShopBrand;
import com.hyyt.shopjsp.product.pojo.ShopProductType;
import com.hyyt.shopjsp.product.service.IShopProductTypeService;
import com.hyyt.shopjsp.redis.service.IRedisInitializingBasicDataService;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;
import com.hyyt.shopjsp.util.redis.service.IRedisBasicService;
import com.hyyt.shopjsp.util.redis.util.RedisDataReadUtil;
import com.hyyt.shopjsp.wxmg.basicInfo.pojo.WxGlobalReturnCode;
import com.hyyt.shopjsp.wxmg.basicInfo.service.IWxGlobalReturnCodeService;
import com.hyyt.shopjsp.wxmg.publicNo.pojo.WxPublicNoInfo;
import com.hyyt.shopjsp.wxmg.publicNo.service.IWxPublicNoInfoService;
import com.hyyt.shopjsp.wxmg.util.WxBasicUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Redis 初始化数据基础Service实现类
 *
 * @author ankang on 2016/7/1 0001.
 */
@Service
public class RedisInitializingBasicDataService implements IRedisInitializingBasicDataService {

    /**
     * 注入数据字典
     **/
    @Resource
    protected IBasicKeyBookService keybookService;

    /**
     * 注入系统配置
     **/
    @Resource
    protected IBasicSystemConfigService systemconfigService;

    /**
     * 注入redis操作
     */
    @Resource
    private IRedisBasicService redisBasicService;

    /**
     * 注入PC首页数据字典
     **/
    @Resource
    private IShopHomeKeyBookService shopHomeKeyBookService;//数据字典service接口

    /**
     * 注入手机数据字典
     **/
    @Resource
    private IPhoneHomeKeyBookService phoneHomeKeyBookService;//数据字典service接口

    /**
     * 产品分类service
     **/
    @Resource
    private IShopProductTypeService productTypeService;

    /**
     * 微信基础信息service
     */
    @Resource
    private IWxPublicNoInfoService wxPublicNoInfoService;

    /**
     * 微信全局返回码service
     */
    @Resource
    private IWxGlobalReturnCodeService wxGlobalReturnCodeService;

    /**
     * 将数据字典初始化到Redis中
     *
     * @return boolean
     */
    @Override
    public boolean initKeyBookDataInfo() {
        boolean result = false;//声明一个变量result
        List<BasicKeyBook> keybookList = keybookService.getAllType();//查询要加载的数据（通过type进行了去重）
        if (Utils.collectionIsNotEmpty(keybookList)) {
            result = true;//查询到数据 将result更改为true
            for (BasicKeyBook keybook : keybookList) {
                String type = keybook.getType();
                List<BasicKeyBook> findKeyBookByType = keybookService.queryKeyBookByType(type);   //通过type查询对应的集合
                if (findKeyBookByType != null && findKeyBookByType.size() > 0) {
                    String jsonString = FastJsonUtils.toJSONString(findKeyBookByType);//将value格式化成json格式
                    redisBasicService.setKey(StringStaticKey.KEYBOOK_PREFIX + type, jsonString); //将查询结果放入redis
                }
            }
        }
        return result;
    }

    /**
     * 将数据字典初始化到Redis中
     *
     * @return boolean
     */
    @Override
    public boolean initKeyBookStatusRelate() {
        boolean result = false;//声明一个变量result
        List<String> typeList = keybookService.getStatusRelateType();//查询要加载的数据（通过type进行了去重）
        if (Utils.collectionIsNotEmpty(typeList)) {
            result = true;//查询到数据 将result更改为true
            for (String type : typeList) {
                List<BasicStatusRelateVo> statusRelateVoList = keybookService.getStatusRelateByType(type);   //通过type查询对应的集合
                if (Utils.collectionIsNotEmpty(statusRelateVoList)) {
                    String jsonString = FastJsonUtils.toJSONString(statusRelateVoList);//将value格式化成json格式
                    redisBasicService.setKey(StringStaticKey.KEYBOOK_STATUS_PREFIX + type, jsonString); //将查询结果放入redis
                }

            }
        }
        return result;
    }

    /**
     * 将基础数据设置初始化到Redis中
     *
     * @return boolean
     */
    @Override
    public boolean initSystemConfig() {
        //声明一个变量result 默认为false  当字典初始化成功时 将其更改为true
        boolean result = false;
        //查询要加载的数据（通过type进行了去重）
        List<BasicSystemConfig> systemConfigList = systemconfigService.initSystemConfigData();
        if (Utils.collectionIsNotEmpty(systemConfigList)) {
            for (BasicSystemConfig sys : systemConfigList) {
                //通过type查询对应的集合
                redisBasicService.setKey(StringStaticKey.SYSTEMCONFIG_PREFIX + sys.getType(), sys.getValue());
            }
            //为静态map对象赋值
            result = true;//查询到数据 将result更改为true
        }
        return result;
    }


    /**
     * 将PC首页数据字典初始化到Redis中
     *
     * @return boolean
     */
    @Override
    public boolean initHomeKeyBookDataInfo() {
        Map<String, Object> param = new HashMap<>();
        boolean result = false;//声明一个变量result
        List<String> typeList = shopHomeKeyBookService.getStatusRelateType();//查询要加载的数据（通过type进行了去重）
        if (Utils.collectionIsNotEmpty(typeList)) {
            for (String type : typeList) {
                param.put("type", type);
                List<ShopHomeKeyBook> shopHomeKeyBookList = shopHomeKeyBookService.queryShopHomeKeyBook(param);   //通过type查询对应的集合
                if (Utils.collectionIsNotEmpty(shopHomeKeyBookList)) {
                    String jsonString = FastJsonUtils.toJSONString(shopHomeKeyBookList);//将value格式化成json格式
                    redisBasicService.setKey(StringStaticKey.HOME_KEYBOOK_PREFIX + type, jsonString); //将查询结果放入redis
                }
            }
            result = true;//查询到数据 将result更改为true
        }
        return result;
    }

    /**
     * 将手机数据字典初始化到Redis中
     *
     * @return boolean
     */
    @Override
    public boolean initPhoneKeyBookDataInfo() {
        Map<String, Object> param = new HashMap<>();
        boolean result = false;//声明一个变量result
        List<String> typeList = phoneHomeKeyBookService.getStatusRelateType();//查询要加载的数据（通过type进行了去重）
        if (Utils.collectionIsNotEmpty(typeList)) {
            for (String type : typeList) {
                param.put("type", type);
                List<PhoneHomeKeyBook> phoneKeyBookList = phoneHomeKeyBookService.queryPhoneHomeKeyBook(param);   //通过type查询对应的集合
                if (Utils.collectionIsNotEmpty(phoneKeyBookList)) {
                    String jsonString = FastJsonUtils.toJSONString(phoneKeyBookList);//将value格式化成json格式
                    redisBasicService.setKey(StringStaticKey.PHONE_KEYBOOK_PREFIX + type, jsonString); //将查询结果放入redis
                }
            }
            result = true;//查询到数据 将result更改为true
        }
        return result;
    }

    /**
     * 初始化全局地区信息，暂未实现
     *
     * @return
     */
    @Override
    public boolean initBasicArea() {
        return false;
    }

    /**
     * 通过三级分类的id查询所有级别的分类名称组合
     *
     * @param productTypeId
     * @return
     */
    @Override
    public String getProductTypeNameById(Integer productTypeId) {
        StringBuffer sb = new StringBuffer();
        List<AllProductTypeVo> productTypeVos = RedisDataReadUtil.getProductType();
        for (AllProductTypeVo shopProductType : productTypeVos) {
            List<AllProductTypeVo> shopProductTypeList = shopProductType.getProductTypeList();
            for (AllProductTypeVo shopProductType1 : shopProductTypeList) {
                List<AllProductTypeVo> productTypeVoList = shopProductType1.getProductTypeList();
                for (AllProductTypeVo shopProductType2 : productTypeVoList) {
                    if (shopProductType2.getProductTypeId().equals(productTypeId)) {
                        sb.append(shopProductType.getSortName()).append(">>").append(shopProductType1.getSortName()).append(">>").append(shopProductType2.getSortName());
                    }
                }
            }
        }
        return sb.toString();
    }


    /**
     * 初始化微信基础信息
     * @return
     */
    @Override
    public boolean initWxPublicNoInfoAccessToken(){
        boolean result = false;//声明一个变量result
        //根据配置表信息查询是否开启微信初始化 accessToken
        String isAccessTokenOpen = RedisDataReadUtil.getSysConfig("weixin_is_open_access_token");
        if(Utils.objectIsNotEmpty(isAccessTokenOpen) && "true".equals(isAccessTokenOpen)){
            WxPublicNoInfo wxPublicNoInfo = wxPublicNoInfoService.loadUniqueWxPublicNoInfo();
            String accessToken = WxBasicUtil.getAccessToken(wxPublicNoInfo.getAppId(), wxPublicNoInfo.getAppSecret());
            redisBasicService.setKey(StringStaticKey.WX_PUBLIC_NO_INFO,FastJsonUtils.toJSONString(wxPublicNoInfo));
            redisBasicService.setKey(StringStaticKey.WX_ACCESS_TOKENS,accessToken);
            String ticket = WxBasicUtil.getTicket(accessToken);
            if(Utils.objectIsNotEmpty(ticket)){
                redisBasicService.setKey(StringStaticKey.WX_TICKET,ticket);
            }
            result=true;
        }
        return result;
    }

    /**
     * 初始化微信全局返回码
     * @return
     */
    @Override
    public boolean initWxGlobalReturnCode(){
        boolean result = false;//声明一个变量result
        //查询微信全局返回码
        List<WxGlobalReturnCode> wxGlobalReturnCodeList = wxGlobalReturnCodeService.queryAllWxGlobalReturnCode();
        redisBasicService.setKey(StringStaticKey.WX_GLOBAL_RETURN_CODE,FastJsonUtils.toJSONString(wxGlobalReturnCodeList));
        result=true;
        return result;
    }

}
